<template>
  <div class="version-management-page">
    <el-card class="version-management-page__header">
      <div class="latest-version-box">
        <el-input v-model="client1LatestVersion" readonly>
          <template #prepend>
            <div class="ver_box">
              <span v-show="lang === 'cn'"> DentalScanner {{ $t('versionManagement.version17') }} </span>
              <el-tooltip v-if="lang !== 'cn'" class="item" effect="dark"
                :content="'DentalScanner ' + $t('versionManagement.version17')" placement="top-start">
                <span> DentalScanner {{ $t('versionManagement.version17') }} </span>
              </el-tooltip>
              <el-select v-model="versionType1" :placeholder="$t('versionManagement.version35')"
                @change="versionType('1')">
                <el-option v-for="item in versionTypes" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
          </template>
        </el-input>
        <el-input v-model="client2LatestVersion" readonly>
          <template #prepend>
            <div class="ver_box">
              <span v-show="lang === 'cn'"> IntraoralScanner {{ $t('versionManagement.version17') }} </span>
              <el-tooltip v-if="lang !== 'cn'" class="item" effect="dark"
                :content="'IntraoralScanner ' + $t('versionManagement.version17')" placement="top-start">
                <span> IntraoralScanner {{ $t('versionManagement.version17') }} </span>
              </el-tooltip>
              <el-select v-model="versionType2" :placeholder="$t('versionManagement.version35')"
                @change="versionType('2')">
                <el-option v-for="item in versionTypes" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
          </template>
        </el-input>

        <el-input v-model="client3LatestVersion" readonly>
          <template #prepend>
            <div class="ver_box">
              <span v-show="lang === 'cn'"> Ortho {{ $t('versionManagement.version17') }} </span>
              <el-tooltip v-if="lang !== 'cn'" class="item" effect="dark"
                :content="'Ortho ' + $t('versionManagement.version17')" placement="top-start">
                <span> Ortho {{ $t('versionManagement.version17') }} </span>
              </el-tooltip>

              <el-select v-model="versionType3" :placeholder="$t('versionManagement.version35')"
                @change="versionType('3')">
                <el-option v-for="item in versionTypes" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
          </template>
        </el-input>
        <el-input v-model="client4LatestVersion" readonly>
          <template #prepend>
            <div class="ver_box">
              <span v-show="lang === 'cn'"> OrthoSimulator {{ $t('versionManagement.version17') }} </span>
              <el-tooltip v-if="lang !== 'cn'" class="item" effect="dark"
                :content="'OrthoSimulator ' + $t('versionManagement.version17')" placement="top-start">
                <span> OrthoSimulator {{ $t('versionManagement.version17') }} </span>
              </el-tooltip>
              <el-select v-model="versionType4" :placeholder="$t('versionManagement.version35')"
                @change="versionType('4')">
                <el-option v-for="item in versionTypes" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
          </template>
        </el-input>

        <el-input v-model="client5LatestVersion" readonly>
          <template #prepend>
            <div class="ver_box">
              <span v-show="lang === 'cn'"> DentalImage {{ $t('versionManagement.version17') }} </span>
              <el-tooltip v-if="lang !== 'cn'" class="item" effect="dark"
                :content="'DentalImage ' + $t('versionManagement.version17')" placement="top-start">
                <span>DentalImage {{ $t('versionManagement.version17') }} </span>
              </el-tooltip>
              <el-select v-model="versionType5" :placeholder="$t('versionManagement.version35')"
                @change="versionType('5')">
                <el-option v-for="item in versionTypes" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
          </template>
        </el-input>

        <el-input v-model="client6LatestVersion" readonly>
          <template #prepend>
            <div class="ver_box">
              <span v-show="lang === 'cn'"> Splintdesign {{ $t('versionManagement.version17') }} </span>
              <el-tooltip v-if="lang !== 'cn'" class="item" effect="dark"
                :content="'Splintdesign ' + $t('versionManagement.version17')" placement="top-start">
                <span>Splintdesign {{ $t('versionManagement.version17') }} </span>
              </el-tooltip>
              <el-select v-model="versionType6" :placeholder="$t('versionManagement.version35')"
                @change="versionType('6')">
                <el-option v-for="item in versionTypes" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
          </template>
        </el-input>

        <el-input v-model="client7LatestVersion" readonly>
          <template #prepend>
            <div class="ver_box">
              <span v-show="lang === 'cn'"> Crowndesign {{ $t('versionManagement.version17') }} </span>
              <el-tooltip v-if="lang !== 'cn'" class="item" effect="dark"
                :content="'Crowndesign ' + $t('versionManagement.version17')" placement="top-start">
                <span>Crowndesign {{ $t('versionManagement.version17') }} </span>
              </el-tooltip>
              <el-select v-model="versionType7" :placeholder="$t('versionManagement.version35')"
                @change="versionType('7')">
                <el-option v-for="item in versionTypes" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
          </template>
        </el-input>
      </div>

      <div class="version-management-page__header-inputs">
        <el-input v-model="queryCriteria.version" :placeholder="$t('versionManagement.version11')" :clearable="true" />
        <el-input v-model="queryCriteria.fileName" :placeholder="$t('versionManagement.version14')" :clearable="true" />
        <el-date-picker v-model="queryCriteria.date" :end-placeholder="$t('versionManagement.version13')"
          :start-placeholder="$t('versionManagement.version12')" type="daterange" value-format="yyyy-MM-dd" />
        <el-select v-model="queryCriteria.clientType" :placeholder="$t('versionManagement.version15')"
          :clearable="true">
          <el-option v-for="option in clientTypeOptions" :key="option.value" :label="option.label"
            :value="option.value" />
        </el-select>
      </div>
      <div class="version-management-page__header-buttons">
        <el-button type="primary" icon="el-icon-search" @click="toSearch">
          {{ $t('versionManagement.version16') }}
        </el-button>
      </div>
    </el-card>
    <el-card class="version-management-page__body">
      <div class="version-management-page__body-tool-buttons">
        <el-button icon="el-icon-plus" type="primary" size="small" @click="onAdd()">
          {{ $t('versionManagement.version01') }}
        </el-button>
      </div>
      <div class="version-management-page__body-content">
        <el-table :data="tableData">
          <el-table-column :label="$t('versionManagement.version04')" align="center" prop="version" />
          <el-table-column :label="$t('versionManagement.version05')" align="center" prop="uploadTime" />
          <el-table-column :label="$t('versionManagement.version06')" align="center" prop="uploadUser" />
          <el-table-column :label="$t('versionManagement.version07')" align="center" prop="fileSize">
            <template #default="scope">{{ scope.row.fileSize }}</template>
          </el-table-column>
          <el-table-column :label="$t('versionManagement.version09')" align="center" prop="fileName"
            show-overflow-tooltip />
          <el-table-column :label="$t('versionManagement.version10')" align="center" prop="clientType">
            <template #default="scope">{{ getClientTypeLabel(scope.row.clientType) }}</template>
          </el-table-column>
          <el-table-column :label="$t('versionManagement.version08')" align="center" prop="description"
            show-overflow-tooltip />
          <el-table-column :label="$t('versionManagement.version26')" align="center" width="160">
            <template #default="scope">
              <el-button type="primary" size="mini" @click="onEdit(scope.row)">
                {{ $t('versionManagement.version27') }}
              </el-button>
              <el-button type="danger" size="mini" @click="onDelete(scope.row)">
                {{ $t('versionManagement.version28') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination background :current-page="pageable.page" :page-size="pageable.pageSize"
        :page-sizes="[10, 20, 50, 100]" :total="pageable.total" layout="total, sizes, prev, pager, next, jumper"
        @size-change="onPageSizeChange" @current-change="onPageChange" />
    </el-card>
    <el-dialog :visible.sync="uploadDialog.visible" :title="$t('versionManagement.version01')"
      :close-on-press-escape="false" :close-on-click-modal="false" :destroy-on-close="true"
      class="version-upload-dialog" width="30%" @open="onUploadDialogOpen" @close="onUploadDialogClose">
      <el-form ref="uploadFormRef" :model="uploadDialog.formModel" :rules="uploadDialog.formRules" label-width="100px"
        label-position="right" :disabled="uploadDialog.saveLoading">
        <el-form-item :label="`${$t('versionManagement.version10')}: `" prop="client_type">
          <el-select v-model="uploadDialog.formModel.client_type" :placeholder="$t('versionManagement.version15')"
            :disabled="status === 'edit'">
            <el-option v-for="option in clientTypeOptions" :key="option.value" :value="option.value"
              :label="option.label" />
          </el-select>
        </el-form-item>
        <el-form-item :label="`${$t('versionManagement.version04')}: `" prop="version">
          <el-input v-model="uploadDialog.formModel.version" :placeholder="$t('versionManagement.version11')"
            :disabled="uploadDialog.formModel.client_type === '' || status === 'edit'" />
        </el-form-item>
        <el-form-item :label="`${$t('versionManagement.language')}: `" prop="language" class="language-box">
          <el-radio-group v-model="uploadDialog.language_type">
            <el-radio :label="1">中文-Chinese</el-radio>
            <el-radio :label="2">英语-English</el-radio>
            <el-radio :label="3">法语-French</el-radio>
            <el-radio :label="4">西班牙语-Spain</el-radio>
            <el-radio :label="5">俄语-Russian</el-radio>
            <el-radio :label="6">意大利语-Italian</el-radio>
            <el-radio :label="7">葡萄牙语-Portuguese</el-radio>
            <el-radio :label="8">繁体中文-Tw</el-radio>
            <el-radio :label="9">土耳其语-Tr</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="`${$t('versionManagement.version08')}: `">
          <!-- 中文 -->
          <el-input v-show="uploadDialog.language_type === 1" v-model="uploadDialog.formModel.description"
            type="textarea" :rows="5" :placeholder="$t('versionManagement.version19')"
            :disabled="uploadDialog.formModel.client_type === ''" />

          <!-- 英文 -->
          <el-input v-show="uploadDialog.language_type === 2" v-model="uploadDialog.formModel.descriptionEnglish"
            type="textarea" :rows="5" :placeholder="$t('versionManagement.version19')"
            :disabled="uploadDialog.formModel.client_type === ''" />

          <!-- 法语 -->
          <el-input v-show="uploadDialog.language_type === 3" v-model="uploadDialog.formModel.descriptionFrench"
            type="textarea" :rows="5" :placeholder="$t('versionManagement.version19')"
            :disabled="uploadDialog.formModel.client_type === ''" />

          <!-- 西班牙语 -->
          <el-input v-show="uploadDialog.language_type === 4" v-model="uploadDialog.formModel.descriptionSpain"
            type="textarea" :rows="5" :placeholder="$t('versionManagement.version19')"
            :disabled="uploadDialog.formModel.client_type === ''" />
          <!-- 俄语 -->
          <el-input v-show="uploadDialog.language_type === 5" v-model="uploadDialog.formModel.descriptionRussian"
            type="textarea" :rows="5" :placeholder="$t('versionManagement.version19')"
            :disabled="uploadDialog.formModel.client_type === ''" />
          <!-- 意大利语 -->
          <el-input v-show="uploadDialog.language_type === 6" v-model="uploadDialog.formModel.descriptionItaly"
            type="textarea" :rows="5" :placeholder="$t('versionManagement.version19')"
            :disabled="uploadDialog.formModel.client_type === ''" />

          <!-- 葡萄牙语 -->
          <el-input v-show="uploadDialog.language_type === 7" v-model="uploadDialog.formModel.descriptionPortuguese"
            type="textarea" :rows="5" :placeholder="$t('versionManagement.version19')"
            :disabled="uploadDialog.formModel.client_type === ''" />

          <!-- 繁体 -->
          <el-input v-show="uploadDialog.language_type === 8" v-model="uploadDialog.formModel.descriptionTw"
            type="textarea" :rows="5" :placeholder="$t('versionManagement.version19')"
            :disabled="uploadDialog.formModel.client_type === ''" />
          <el-input v-show="uploadDialog.language_type === 9" v-model="uploadDialog.formModel.descriptionTurkish"
            type="textarea" :rows="5" :placeholder="$t('versionManagement.version19')"
            :disabled="uploadDialog.formModel.client_type === ''" />
        </el-form-item>
        <el-form-item :label="`${$t('versionManagement.version21')}: `">
          <el-upload ref="upload" :file-list="uploadDialog.fileList" action="#" accept=".zip,.7z"
            :show-file-list="false" :multiple="false" :limit="1" :http-request="upload" :before-upload="beforeUpload"
            :on-exceed="onUploadExceed" :on-change="onUploadChange">
            <el-button type="primary" @click="handleUploadClick">{{ $t('versionManagement.version22') }}</el-button>
            <div slot="tip" class="el-upload__tip">{{ $t('versionManagement.version63') }}</div>
          </el-upload>
          <div>
            <span class="fileName" v-show="uploadFile && uploadFile.name">{{ uploadFile.name }}
              <span class="fileClose" @click="onUploadRemove">x</span>
            </span>
            <span class="fileSize" v-show="uploadFile && uploadFile.size">{{
              formatSize(uploadFile.size)
            }}</span>
            <div>
              <!-- <div class="parse">
                <span>{{ $t('versionManagement.analysisProgress') }}： </span>
                <el-progress :text-inside="true" :stroke-width="16" :percentage="uploadFile.parsePercentage" text-color="#FFFFFF">
                </el-progress>
              </div> -->
              <div class="progress">
                <span>{{ $t('versionManagement.uploadProgress') }}：</span>

                <el-progress :text-inside="true" :stroke-width="16" :percentage="uploadFile.uploadPercentage"
                  text-color="#FFFFFF" />
                <span v-if="(uploadFile.uploadPercentage > 0) & (uploadFile.uploadPercentage < 100)">
                  <span class="uploadSpeed">{{ uploadFile.uploadSpeed }}</span>

                  <!-- <el-button circle link @click="changeUploadingStop(uploadFile)">
            <el-icon size="20" v-if="uploadFile.uploadingStop == false"
              ><VideoPause
            /></el-icon>
            <el-icon size="20" v-else><VideoPlay /></el-icon>
          </el-button> -->
                </span>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :disabled="uploadDialog.saveLoading" @click="uploadDialog.visible = false">
            {{ $t('versionManagement.version03') }}
          </el-button>
          <el-button type="primary" :loading="uploadDialog.saveLoading" :disabled="submitDisabled"
            @click="onUploadDialogConfirm">
            {{ $t('versionManagement.version02') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs';
import SparkMD5 from 'spark-md5';
import { versionReg } from '@/utils/validate';

export default {
  name: 'VersionManagement',
  data() {
    const validateVersion = (rule, value, callback) => {
      if (!value) {
        return callback(new Error(this.$t('versionManagement.version20')));
      }
      let num = value.split('.')[3];
      if (num && num.length > 1) {
        return callback(new Error(this.$t('versionManagement.version20')));
      } else {
        callback();
      }
    };
    return {
      queryCriteria: {
        version: '',
        date: [],
        fileName: '',
        clientType: '',
      },
      pageable: {
        total: 0,
        page: 1,
        pageSize: 10,
      },
      clientTypeOptions: [
        {
          value: '1',
          label: 'DentalScanner',
        },
        {
          value: '2',
          label: 'IntraoralScanner',
        },
        {
          value: '3',
          label: 'Ortho',
        },
        {
          value: '4',
          label: 'OrthoSimulator',
        },
        {
          value: '5',
          label: 'DentalImage',
        },
        {
          value: '6',
          label: 'Splintdesign',
        },
        {
          value: '7',
          label: 'Crowndesign',
        },
      ],
      tableData: [],

      client1LatestVersion: '',
      client2LatestVersion: '',
      client3LatestVersion: '',
      client4LatestVersion: '',
      client5LatestVersion: '',
      client6LatestVersion: '',
      client7LatestVersion: '',
      selectedRow: undefined,
      versionType1: '0000',
      versionType2: '0000',
      versionType3: '1000',
      versionType4: '1000',
      versionType5: '0000',
      versionType6: '0000',
      versionType7: '0000',
      versionTypes: [
        {
          label: '0000',
          value: '0000',
        },
        {
          label: '1000',
          value: '1000',
        },
      ],
      uploadDialog: {
        visible: false,
        fileList: [],
        language_type: 1,
        formModel: {
          version: '',
          description: '',
          descriptionEnglish: '',
          descriptionFrench: '',
          descriptionSpain: '',
          descriptionRussian: '',
          descriptionItaly: '',
          descriptionPortuguese: '',
          descriptionTw: '',
          descriptionTurkish: '',
          client_type: '',
        },
        formRules: {
          version: [
            {
              required: true,
              validator: validateVersion,
              trigger: 'blur',
            },

            {
              pattern: versionReg(),
              message: this.$t('versionManagement.version20'),
              trigger: 'blur',
            },
          ],
          client_type: [
            {
              required: true,
              message: this.$t('versionManagement.version15'),
              trigger: ['blur', 'change'],
            },
          ],
        },
        saveLoading: false,
      },
      uploadFile: {},
      status: 'add',
      // 定义一个变量判断是否重复文件
      isRepeat: false,

      //  定义一个变量是否继续切片请求
      isNextAjax: true,
      lang: false,

      submitDisabled: true,
    };
  },

  created() {
    this.fetchClientLatestVersion();
    this.lang = window.localStorage.getItem('lang');
  },
  mounted() {
    this.fetchVersionList();
  },
  methods: {

    toSearch() {
      this.pageable.page = 1;
      this.fetchVersionList();
    },
    fetchVersionList() {
      let startTime = '';
      let endTime = '';
      if (this.queryCriteria.date && this.queryCriteria.date.length > 0) {
        startTime = this.queryCriteria.date[0];
        endTime = this.queryCriteria.date[1];
      }
      const { version, fileName, clientType } = this.queryCriteria;
      const { page, pageSize: limit } = this.pageable;
      const paramStr = `version=${version}&file_name=${fileName}&start_time=${startTime}&end_time=${endTime}&client_type=${clientType}&page=${page}&limit=${limit}`;
      this.$http
        .get(`versioning/getVersionList?${paramStr}`)
        .then(({ data: res }) => {
          if (res.code === 0 && res.data) {
            const { list, total } = res.data;
            this.tableData = list;
            this.pageable.total = total;
            if (this.tableData.length <= 0 && this.pageable.page > 1) {
              this.pageable.page -= 1;
              this.fetchVersionList();
            }
          } else {
            console.log(res);
          }
        })
        .catch((e) => console.error(e));
    },

    onUploadDialogOpen() {
      this.isNextAjax = true;
      if (this.selectedRow !== undefined) {
        const {
          version,
          uploadTime,
          clientType,
          description,
          descriptionEnglish,
          descriptionFrench,
          descriptionSpain,
          descriptionRussian,
          descriptionItaly,
          descriptionPortuguese,
          descriptionTw,
          descriptionTurkish,
          url,
          fileName,
          id,
        } = this.selectedRow;
        this.uploadDialog.formModel.version = version;
        this.uploadDialog.formModel.upload_time = uploadTime;
        this.uploadDialog.formModel.client_type = clientType;
        this.uploadDialog.formModel.description = description;
        this.uploadDialog.formModel.descriptionEnglish = descriptionEnglish;
        this.uploadDialog.formModel.descriptionFrench = descriptionFrench;
        this.uploadDialog.formModel.descriptionSpain = descriptionSpain;
        this.uploadDialog.formModel.descriptionRussian = descriptionRussian;
        this.uploadDialog.formModel.descriptionItaly = descriptionItaly;
        this.uploadDialog.formModel.descriptionPortuguese = descriptionPortuguese;
        this.uploadDialog.formModel.descriptionTw = descriptionTw;
        this.uploadDialog.formModel.descriptionTurkish = descriptionTurkish;
        
        this.uploadDialog.fileList = [{ name: fileName, url, cId: id }];
        this.uploadFile = { name: fileName, url, cId: id };
        if (fileName) {
          this.submitDisabled = false;
        } else {
          this.submitDisabled = true;
        }

      } else {
        this.uploadDialog.formModel.upload_time = dayjs().toDate();
        this.submitDisabled = true;
      }

    },
    onUploadDialogClose() {
      this.$refs.uploadFormRef.resetFields();
      this.uploadDialog.language_type = 1;
      this.uploadDialog.formModel.version = '';
      this.uploadDialog.formModel.description = '';
      this.uploadDialog.formModel.descriptionEnglish = '';
      this.uploadDialog.formModel.descriptionFrench = '';
      this.uploadDialog.formModel.descriptionSpain = '';
      this.uploadDialog.formModel.descriptionRussian = '';
      this.uploadDialog.formModel.descriptionItaly = '';
      this.uploadDialog.formModel.descriptionPortuguese = '';
      this.uploadDialog.formModel.descriptionTw = '';
      this.uploadDialog.formModel.descriptionTurkish = '';
      
      this.uploadDialog.formModel.upload_time = '';
      this.uploadDialog.formModel.client_type = '';

      this.uploadDialog.fileList = [];
      this.selectedRow = undefined;
      this.isNextAjax = false;
    },
    onUploadDialogConfirm() {
      this.$refs.uploadFormRef.validate((valid) => {
        if (valid) {
          if (this.uploadDialog.fileList.length === 0) {
            this.$message.warning(this.$t('versionManagement.version24'));
            return;
          }
          if (this.isRepeat) {
            this.$message.warning(this.$t('versionManagement.uploadRepeatMsg'));
            return;
          }
          const currentVersion =
            this.uploadDialog.formModel.client_type === '1'
              ? this.client1LatestVersion
              : this.client2LatestVersion;
          if (currentVersion !== '' && currentVersion !== undefined && currentVersion !== null) {
            const currentVersionNum = Number.parseInt(
              currentVersion.replace('V', '').replaceAll('.', ''),
            );
            const inputVersionNum = Number.parseInt(
              this.uploadDialog.formModel.version.replace('V', '').replaceAll('.', ''),
            );
            // if (this.status === 'add' && currentVersionNum >= inputVersionNum) {
            //   this.$message.warning(this.$t('versionManagement.version34'));
            //   return;
            // }
          }
          this.uploadDialog.saveLoading = true;

          const formData = new FormData();
          formData.append('version', this.uploadDialog.formModel.version);
          formData.append('upload_time', dayjs().format('YYYY-MM-DD HH:mm:ss'));
          formData.append('description', this.uploadDialog.formModel.description);
          formData.append('descriptionEnglish', this.uploadDialog.formModel.descriptionEnglish);
          formData.append('descriptionFrench', this.uploadDialog.formModel.descriptionFrench);
          formData.append('descriptionSpain', this.uploadDialog.formModel.descriptionSpain);
          formData.append('descriptionRussian', this.uploadDialog.formModel.descriptionRussian);
          formData.append('descriptionItaly', this.uploadDialog.formModel.descriptionItaly);
          formData.append('descriptionPortuguese', this.uploadDialog.formModel.descriptionPortuguese);
          formData.append('descriptionTw', this.uploadDialog.formModel.descriptionTw);
          formData.append('descriptionTurkish', this.uploadDialog.formModel.descriptionTurkish);
          
          formData.append('client_type', this.uploadDialog.formModel.client_type);
          formData.append('upload_user', localStorage.getItem('user_id'));

          if (this.selectedRow !== undefined) {
            formData.append('id', this.selectedRow.id);
          }
          formData.append('md5', this.uploadFile.md5 ? this.uploadFile.md5 : '');
          if (this.uploadFile.size) {
            formData.append('fileSize', this.formatSize(this.uploadFile.size));
          }
          formData.append('fileName', this.uploadFile.name);
          formData.append('uploadUser', localStorage.getItem('user_id'));

          if (this.selectedRow !== undefined) {
            this.$http
              .post('versioning/update', formData)
              .then((res) => {
                if (res.data.code !== 0) {
                  this.uploadDialog.saveLoading = false;
                  return this.$message.error(res.data.msg);
                } else {
                  this.$message.success(this.$t('versionManagement.version25'));
                  this.uploadDialog.visible = false;
                  this.uploadDialog.saveLoading = false;

                  this.fetchVersionList();
                  this.fetchClientLatestVersion();
                }
              })
              .catch((e) => {
                this.uploadDialog.saveLoading = false;
                console.error(e);
              });
          } else {
            this.$http
              .post('versioning/save', formData)
              .then((res) => {
                console.log('res--------', res);
                if (res.data.code !== 0) {
                  this.uploadDialog.saveLoading = false;
                  return this.$message.error(res.data.msg);
                } else {
                  this.$message.success(this.$t('versionManagement.version25'));
                  this.uploadDialog.visible = false;
                  this.uploadDialog.saveLoading = false;

                  this.fetchVersionList();
                  this.fetchClientLatestVersion();
                }
              })
              .catch((e) => {
                this.uploadDialog.saveLoading = false;
                console.error(e);
              });
          }
        }
      });
    },
    upload(xhrData) {
      if (this.uploadFile && this.uploadFile.needUpload) {
        // 分片上传文件
        // 确定分片的大小
        this.uploadChunk(xhrData.file, 1, this.uploadFile);
      }
    },

    uploadChunk(file, index, uploadFile) {
      if (!this.isNextAjax) {
        return false;
      }
      var chunkSize = 1024 * 1024 * 20; //10mb
      var chunkTotal = Math.ceil(file.size / chunkSize);
      if (index <= chunkTotal) {
        // 根据是否暂停，确定是否继续上传
        // console.log("4.上传分片");
        var startTime = new Date().valueOf();
        var exit = uploadFile.chunkList.includes(index);
        // console.log("是否存在",exit);
        if (!exit) {
          //    console.log("3.3上传文件",uploadingStop);
          if (!uploadFile.uploadingStop) {
            // 分片上传，同时计算进度条和上传速度
            // 已经上传的不在上传、
            // 上传完成后提示，上传成功
            // console.log("上传分片1",index);
            var form = new FormData();
            var start = (index - 1) * chunkSize;
            let end = index * chunkSize >= file.size ? file.size : index * chunkSize;
            let chunk = file.slice(start, end);
            form.append('chunk', chunk);
            form.append('index', index);
            form.append('chunkTotal', chunkTotal);
            form.append('chunkSize', chunkSize);
            form.append('md5', uploadFile.md5);
            form.append('fileSize', file.size);
            form.append('fileName', file.name);
            // console.log("上传分片", index);
            this.$http.post('bigFile/upload/chunk', form).then((res) => {
              var endTime = new Date().valueOf();
              var timeDif = (endTime - startTime) / 1000;
              uploadFile.uploadSpeed = (10 / timeDif).toFixed(1) + ' M/s';
              uploadFile.chunkList.push(index);
              uploadFile.uploadPercentage = parseInt(
                (uploadFile.chunkList.length / chunkTotal) * 100,
              );
              console.log('uploadFile.uploadPercentage---', uploadFile.uploadPercentage);
              if (uploadFile.uploadPercentage >= 100) {
                this.submitDisabled = false;
              }

              if (res.data.data == chunkTotal) {
                this.uploadDialog.saveLoading = false;
              }
              this.uploadChunk(file, index + 1, uploadFile);
            }).catch((err) => {

              this.uploadChunk(file, index, uploadFile);
            });
          }
        } else {
          uploadFile.uploadPercentage = parseInt((uploadFile.chunkList.length / chunkTotal) * 100);
          this.uploadChunk(file, index + 1, uploadFile);
        }
      }
    },
    async beforeUpload(file) {

      this.submitDisabled = true;
      const FIVE_M = 1000 * 1024 * 1024;
      //不允许上传大于2M
      if (file.size > FIVE_M) {
        this.$message.error(this.$t('versionManagement.uploadSizeLimitation'));
        this.uploadDialog.fileList = [];
        return false;
      }
      let fileName = file.name;
      let reg = /^.+(\.zip|.7z)$/;
      if (!reg.test(fileName)) {
        this.$message.error('只能上传zip和7z!');

        return false;
      }
      var uploadFile = {};
      uploadFile.name = file.name;
      uploadFile.size = file.size;
      uploadFile.parsePercentage = 0;
      uploadFile.uploadPercentage = 0;
      uploadFile.uploadSpeed = '0 M/s';
      uploadFile.chunkList = null;
      uploadFile.file = file;
      uploadFile.uploadingStop = false;

      var md5 = await this.computeMd5(file, uploadFile); //async 和 await配可以实现等待异步函数计算完成
      uploadFile.md5 = md5;
      this.uploadFile = uploadFile;
      var res = await this.checkFile(md5, uploadFile.name); //上传服务器检查，以确认是否秒传

      if (res.data.code === 202) {
        this.isRepeat = true;
        return this.$message({
          message: res.data.message,
          type: 'warning',
        });
      } else {

        this.isRepeat = false;
      }
      var data = res.data.data;

      if (!data.isUploaded) {
        uploadFile.chunkList = data.chunkList;
        uploadFile.needUpload = true;
      } else {
        uploadFile.needUpload = false;
        uploadFile.uploadPercentage = 100;

        // ElMessage({
        //   showClose: true,
        //   message: "文件已秒传",
        //   type: "warning",
        // });
      }
      if (uploadFile.uploadPercentage >= 100) {
        this.submitDisabled = false;
      }
    },
    computeMd5(file, uploadFile) {
      return new Promise((resolve, reject) => {
        //分片读取并计算md5
        const chunkTotal = 100; //分片数
        const chunkSize = Math.ceil(file.size / chunkTotal);
        const fileReader = new FileReader();
        const md5 = new SparkMD5();
        let index = 0;
        const loadFile = (uploadFile) => {
          uploadFile.parsePercentage = parseInt((index / file.size) * 100);
          const slice = file.slice(index, index + chunkSize);
          fileReader.readAsBinaryString(slice);
        };
        loadFile(uploadFile);
        fileReader.onload = (e) => {
          md5.appendBinary(e.target.result);
          if (index < file.size) {
            index += chunkSize;
            loadFile(uploadFile);
          } else {
            // md5.end() 就是文件md5码
            resolve(md5.end());
          }
        };
      });
    },
    checkFile(md5, fileName) {
      return this.$http.get(`bigFile/check?md5=${md5}&fileName=${fileName}`);
    },
    formatSize(size) {
      if (!size) {
        return false;
      }
      //size的单位大小k
      var unit;
      var units = [' B', ' K', ' M', ' G'];
      var pointLength = 2;
      while ((unit = units.shift()) && size > 1024) {
        size = size / 1024;
      }
      return (
        (unit === 'B' ? size : size.toFixed(pointLength === undefined ? 2 : pointLength)) + unit
      );
    },
    onUploadChange(_, fileList) {
      let reg = /^.+(\.zip|.7z)$/;
      this.uploadDialog.fileList = fileList.filter((f) => reg.test(f.name));
    },
    onUploadRemove() {
      this.uploadDialog.fileList = this.uploadDialog.fileList.filter(
        (f) => f.cId !== this.uploadFile.cId,
      );
      this.uploadFile = {};
      this.isNextAjax = false;
    },
    onUploadExceed() {

      this.$message.warning(this.$t('versionManagement.version23'));
    },
    handleUploadClick(event) {

      if (this.uploadDialog.fileList.length >= 1) {

        event.stopPropagation(); // 阻止默认行为

        this.$message.warning(this.$t('versionManagement.version23'));
        return false;
      }

    },
    onAdd() {
      this.uploadDialog.visible = true;
      this.uploadFile = {};
      this.status = 'add';
    },
    onEdit(row) {
      this.selectedRow = row;
      this.uploadDialog.visible = true;
      this.status = 'edit';
    },
    onDelete(row) {
      this.$confirm(
        this.$t('versionManagement.version30'),
        this.$t('versionManagement.version29'),
        {
          confirmButtonText: this.$t('versionManagement.version31'),
          cancelButtonText: this.$t('versionManagement.version03'),
          callback: (action) => {
            if (action === 'confirm') {
              const formData = new FormData();
              formData.append('id', row.id);
              this.$http
                .post('versioning/delete', formData)
                .then(() => {
                  this.$message.success(this.$t('versionManagement.version32'));
                  this.fetchVersionList();
                })
                .catch((e) => {
                  console.error(e);
                  this.$message.error(`${this.$t('versionManagement.version33')}: ${e}`);
                });
            }
          },
          type: 'warning',
        },
      );
    },

    versionType(type) {
      if (type === '1') {
        this.fetchClient1LatestVersion();
      } else if (type === '2') {
        this.fetchClient2LatestVersion();
      } else if (type === '3') {
        this.fetchClient3LatestVersion();
      } else if (type === '4') {
        this.fetchClient4LatestVersion();
      } else if (type === '5') {
        this.fetchClient5LatestVersion();
      } else if (type === '6') {
        this.fetchClient6LatestVersion();
      } else if (type === '7') {
        this.fetchClient7LatestVersion();
      }
    },
    fetchClientLatestVersion() {
      this.fetchClient1LatestVersion();
      this.fetchClient2LatestVersion();
      this.fetchClient3LatestVersion();
      this.fetchClient4LatestVersion();
      this.fetchClient5LatestVersion();
      this.fetchClient6LatestVersion();
      this.fetchClient7LatestVersion();
    },
    fetchClient1LatestVersion() {
      const formData = new FormData();
      formData.append('clientType', '1');
      formData.append('versionType', this.versionType1);
      this.$http
        .post('/versioning/latestVersion', formData)
        .then(({ data }) => {
          if (data.code === 0) {
            const { latestVersion } = data.data;
            this.client1LatestVersion = latestVersion;
          } else {
            console.error('请求客户端1类型错误: ', data);
          }
        })
        .catch((e) => {
          console.error(e);
        });
    },
    fetchClient2LatestVersion() {
      const formData = new FormData();
      formData.append('clientType', '2');
      formData.append('versionType', this.versionType2);
      this.$http
        .post('/versioning/latestVersion', formData)
        .then(({ data }) => {
          if (data.code === 0) {
            const { latestVersion } = data.data;
            this.client2LatestVersion = latestVersion;
          } else {
            console.error('请求客户端2类型错误: ', data);
          }
        })
        .catch((e) => {
          console.error(e);
        });
    },

    fetchClient3LatestVersion() {
      const formData = new FormData();
      formData.append('clientType', '3');
      formData.append('versionType', this.versionType3);
      this.$http
        .post('/versioning/latestVersion', formData)
        .then(({ data }) => {
          if (data.code === 0) {
            const { latestVersion } = data.data;
            this.client3LatestVersion = latestVersion;
          } else {
            console.error('请求客户端2类型错误: ', data);
          }
        })
        .catch((e) => {
          console.error(e);
        });
    },

    fetchClient4LatestVersion() {
      const formData = new FormData();
      formData.append('clientType', '4');
      formData.append('versionType', this.versionType4);
      this.$http
        .post('/versioning/latestVersion', formData)
        .then(({ data }) => {
          if (data.code === 0) {
            const { latestVersion } = data.data;
            this.client4LatestVersion = latestVersion;
          } else {
            console.error('请求客户端2类型错误: ', data);
          }
        })
        .catch((e) => {
          console.error(e);
        });
    },

    fetchClient5LatestVersion() {
      const formData = new FormData();
      formData.append('clientType', '5');
      formData.append('versionType', this.versionType5);
      this.$http
        .post('/versioning/latestVersion', formData)
        .then(({ data }) => {
          if (data.code === 0) {
            const { latestVersion } = data.data;
            this.client5LatestVersion = latestVersion;
          } else {
            console.error('请求客户端2类型错误: ', data);
          }
        })
        .catch((e) => {
          console.error(e);
        });
    },

    fetchClient6LatestVersion() {
      const formData = new FormData();
      formData.append('clientType', '6');
      formData.append('versionType', this.versionType6);
      this.$http
        .post('/versioning/latestVersion', formData)
        .then(({ data }) => {
          if (data.code === 0) {
            const { latestVersion } = data.data;
            this.client6LatestVersion = latestVersion;
          } else {
            console.error('请求客户端2类型错误: ', data);
          }
        })
        .catch((e) => {
          console.error(e);
        });
    },

    fetchClient7LatestVersion() {
      const formData = new FormData();
      formData.append('clientType', '7');
      formData.append('versionType', this.versionType7);
      this.$http
        .post('/versioning/latestVersion', formData)
        .then(({ data }) => {
          if (data.code === 0) {
            const { latestVersion } = data.data;
            this.client7LatestVersion = latestVersion;
          } else {
            console.error('请求客户端2类型错误: ', data);
          }
        })
        .catch((e) => {
          console.error(e);
        });
    },

    onPageChange(page) {
      this.pageable.page = page;
      this.fetchVersionList();
    },
    onPageSizeChange(pageSize) {
      this.pageable.pageSize = pageSize;
      this.fetchVersionList();
    },
    getClientTypeLabel(value) {
      const index = this.clientTypeOptions.findIndex((e) => e.value === value);
      if (index !== -1) return this.clientTypeOptions[index].label;
      return '';
    },
  },
};
</script>
<style lang="scss">
.version-upload-dialog {
  .el-form {
    .el-form-item {
      .el-form-item__content {
        &>* {
          width: 100%;
        }
      }
    }
  }
}
</style>
<style lang="scss" scoped>
.version-management-page {
  width: 100%;
  height: 100%;

  // --header-height: 140px;
  .version-management-page__header {
    ::v-deep>.el-card__body {
      border-top: 1px solid #003e67;
      margin-top: 173px;
    }
  }

  &__header {
    height: var(--header-height);
    width: 100%;
    padding-top: 20px;
    position: relative;

    .latest-version-box {
      position: absolute;

      top: 20px;
      left: 20px;
      display: flex;
      align-items: center;
      gap: 20px;
      flex-wrap: wrap;

      >div {
        width: 30%;
      }

      .ver_box {

        span {
          display: inline-block;
          width: 190px;
          text-align: center;
          white-space: nowrap;
          /* 防止文本换行 */
          overflow: hidden;
          /* 超出部分隐藏 */
          text-overflow: ellipsis;
          /* 超出部分显示省略号 */
          cursor: pointer;
        }

        >span {
          position: relative;
          top: 2px;
        }

        .el-select {
          width: 110px;
          border-left: 1px solid #dcdfe6;
          margin-left: 10px;
        }
      }
    }

    ::v-deep .el-card__body {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    &-inputs {
      display: flex;
      align-items: center;
      gap: 20px;

      &>* {
        width: 260px;
      }

      .el-date-editor {
        width: 340px;
      }
    }
  }

  &__body {
    margin-top: 20px;
    width: 100%;
    height: calc(100% - var(--header-height) - 20px);

    ::v-deep .el-pagination {
      margin-top: 8px;
    }
  }

  .fileName {
    font-size: 17px;
    display: inline-block;
    width: 100%;
    background: rgb(235, 238, 245);
    margin-top: 10px;
    position: relative;
    padding: 5px;

    .fileClose {
      position: absolute;
      right: 10px;
      cursor: pointer;
    }

    /* width: 80px; */
  }

  .fileSize {
    font-size: 17px;

    /* width: 80px; */
  }

  .language-box {
    .el-radio {
      height: 30px;
    }
  }

  ::v-deep .el-form-item__label {
    text-align: right !important;
    min-width: 100px !important;
  }

  ::v-deep .language-box .el-form-item__content {
    margin-left: 0px !important;
  }

  ::v-deep .el-radio {
    min-width: 170px !important;
    margin-right: 20px !important;
  }
}
</style>
